package cn.itcast.netty.c5;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;

import static cn.itcast.netty.c4.TestSlice.log;
import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;

public class HelloWorldClient {
    public static void main(String[] args) {
       for(int i = 0;i<10;i++){
           m1();
       }
        System.out.println("finish");
    }

    private static void m1() {
        NioEventLoopGroup worker = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(worker)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                            // 会在连接channel建立成功后,触发active事件
                            @Override
                            public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                ByteBuf buf = ctx.alloc().buffer(16);
                                buf.writeBytes(new byte[]{0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17});
                                log(buf);
                                ctx.writeAndFlush(buf);
                                //短链接 没发送一次 重新建立连接一次 可以解决粘包 但是不能解决半包
                                ctx.channel().close();
                            }
                        });
                    }
                });
            ChannelFuture future = bootstrap.connect(new InetSocketAddress("127.0.0.1", 8080)).sync();
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            worker.shutdownGracefully();
        }
    }
}
